import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/entity/rich_text_entity.dart';
import 'package:shopping_group/entity/selectiont_entity.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/modle/more/bloc/more_st_bloc.dart';
import 'package:shopping_group/modle/more/bloc/video_bloc.dart';
import 'package:shopping_group/modle/more/dialog/more_good_dialog_page.dart';
import 'package:shopping_group/modle/more/entity/group_detail_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/ad_video_util.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:shopping_group/view/button_progress_view.dart';
import 'package:bot_toast/bot_toast.dart';
import 'more_to_paly_page.dart';
import 'video_page.dart';

class MoreStPage extends StatefulWidget {
  final String id;
  final String title;
  MoreStPage({Key key, @required this.title, @required this.id})
      : super(key: key);

  @override
  _MoreStPageState createState() => _MoreStPageState();
}

class _MoreStPageState extends State<MoreStPage> {
  List<SelectiontEntity> _listEntity = [];
  List<RichTextEntity> _richList = [];
  // String gzImagePath =
  //     'https://lizhengyouxuan.oss-cn-shanghai.aliyuncs.com/lizhengyouxuan/pingtuan/pt_guizei1.png';
  GroupDetailEntity _groupDetailEntity = GroupDetailEntity();
  MoreStBloc _bloc;
  StreamSubscription _initViewSubscription;
  StreamSubscription _refeshSubscription;
  StreamSubscription _videoCompletetSubscription;
  VideoBloc _videoBloc;
  @override
  void initState() {
    super.initState();
    _bloc = MoreStBloc();
    _bloc.initDate.add(this.widget.id);
    _videoBloc = VideoBloc();
    BaseConstant.groupSpecId = this.widget.id;
    BaseConstant.groupTitle = this.widget.title;
    _richList
      ..add(RichTextEntity()
        ..backgroundColor = Colours.transparent
        ..title = '差'
        ..textColor = Colours.text_2222
        ..size = Dimens.FONT_SIZE_16)
      ..add(RichTextEntity()
        ..backgroundColor = Colours.transparent
        ..title = '0'
        ..textColor = Colours.themeColor
        ..size = Dimens.FONT_SIZE_16)
      ..add(RichTextEntity()
        ..backgroundColor = Colours.transparent
        ..title = '人聚合推广'
        ..textColor = Colours.text_2222
        ..size = Dimens.FONT_SIZE_16);

    _initViewSubscription = eventBus.on<MoreStBlackEvent>().listen((event) {
      // _showDialogView(event.custGroupSpecRelaId);
      switch (event.canDoAction) {
        case BaseConstant.GUAN_GAO:
          _showAdView();
          break;
        case BaseConstant.RE_BUY:
        case BaseConstant.MUST_RE_BUY:
          _showDialogView(event.custGroupSpecRelaId, event.reBuyImgUrl);
          break;
        default:
      }
    });

    _refeshSubscription = eventBus.on<RefreshEvent>().listen((event) {
      _bloc.initDate.add(this.widget.id);
    });

    _videoCompletetSubscription =
        eventBus.on<AvMoreCompleteEvent>().listen((event) {
      if (!mounted) {
        return;
      }

      Map<String, dynamic> data = {};
      data['groupSpecId'] = _groupDetailEntity.groupSpecId;
      data['myLastJoinId'] = _groupDetailEntity.myLastJoinId;
      data['userId'] = BaseConstant.userId;
      _videoBloc.initDate.add(data);
    });
  }

  Future _showDialogView(custGroupSpecRelaId, reBuyImgUrl) async {
    WidgetUtils.attrubuteDialogFuture(
        context,
        MoreGoodDialogPage(
          custGroupSpecRelaId: custGroupSpecRelaId,
          reBuyImgUrl: reBuyImgUrl,
        ),
        barrierDismissible: true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WidgetUtils.showAppar(context, '${this.widget.title}专区'),
      body: Container(
        height: double.infinity,
        decoration: new BoxDecoration(
          color: Colours.gray_f0,
        ),
        child: Stack(
          children: <Widget>[
            SingleChildScrollView(
                scrollDirection: Axis.vertical,
                reverse: false,
                padding: EdgeInsets.all(0.0),
                physics: BouncingScrollPhysics(),
                child: Column(
                  children: <Widget>[
                    _groupView(),
                    SizedBox(
                      height: 8,
                    ),
                    _hdgzView(),
                    SizedBox(
                      height: 8,
                    ),
                  ],
                )),
            Positioned(
              bottom: 0,
              right: 0,
              left: 0,
              top: MediaQuery.of(context).size.height / 2 +
                  MediaQuery.of(context).size.height / 3 -
                  32,
              child: ButtonProgressView.crateCupertinoView(
                  BaseConstant.NONE == _groupDetailEntity.canDoAction
                      ? '暂无法推广'
                      : '立即推广',
                  blackColor: Colours.title_white,
                  textColor: Colours.themeColor, cupertinoCall: () {
                //_showDialogView();
                // if (!BaseConstant.isRealNameAuthen) {
                //   BotToast.showText(text: '请先实名认证');
                //   return;
                // }
                if (ObjectUtil.isEmptyString(_groupDetailEntity.canDoAction)) {
                  return;
                }
                switch (_groupDetailEntity.canDoAction) {
                  case BaseConstant.JOIN:
                  case BaseConstant.RE_BUY:
                    RouteUtil.goParameter(MoreToPalyPage(
                      entity: _groupDetailEntity,
                    ));
                    break;
                  case BaseConstant.GUAN_GAO:
                    _showAdView();
                    break;
                  case BaseConstant.MUST_RE_BUY:
                    _showDialogView(_groupDetailEntity.custGroupSpecRelaId,
                        _groupDetailEntity.reBuyImgUrl);
                    break;
                  case BaseConstant.NONE:
                    BotToast.showText(text: _groupDetailEntity.doRemark);
                    break;
                  default:
                }
              }),
            ),
            // MoreGoodDialogPage(),
          ],
        ),
      ),
    );
  }

  Future _showAdView() async {
    if (context == null) {
      return;
    }
    showDialog(
        context: context,
        barrierDismissible: true,
        builder: (context) {
          return showAlertDialog();
        }).then((var result) {
      if (null == result) {
        return;
      }

      if (result is String && 'yes' == result) {
        // if (!ObjectUtil.isEmptyString(_groupDetailEntity.playXiYi) &&
        //     'Y' == _groupDetailEntity.playXiYi) {
        //   AdVideoUtil.startMoreVd('rv1');
        // } else {
        RouteUtil.goParameter(VideoPage(
          groupSpecId: _groupDetailEntity.groupSpecId,
          myLastJoinId: _groupDetailEntity.myLastJoinId,
          videoUrl: _groupDetailEntity.failSeeVideoUrl,
        ));
        // }
      }
    });
  }

  Widget showAlertDialog() {
    return SimpleDialog(
      title: WidgetUtils.getTextColorView(
          '提示', Colours.text_2222, Dimens.FONT_SIZE_18),
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 4),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Padding(
                padding:
                    const EdgeInsets.symmetric(vertical: 24, horizontal: 8),
                child: WidgetUtils.getTextColorView(
                    '观看广告', Colours.gray_91, Dimens.FONT_SIZE_16),
              ),
              WidgetUtils.drawCodeDivider(height: 1, color: Colours.themeColor),
              SizedBox(
                height: 16,
              ),
              GestureDetector(
                onTap: () {
                  Navigator.of(context).pop('yes');
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8),
                  child: WidgetUtils.getTextColorView(
                      '去观看', Colours.themeColor, Dimens.FONT_SIZE_20),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _groupView() {
    return StreamBuilder(
      stream: _bloc.sendData,
      initialData: _groupDetailEntity,
      builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
        Object object = snapshot.data;
        if (object is GroupDetailEntity) {
          _groupDetailEntity = object;
        }
        _listEntity = _groupDetailEntity.listEntity;
        _richList = _groupDetailEntity.richList;

        return Column(
          children: <Widget>[
            _groupfzView(),
            SizedBox(
              height: 8,
            ),
            _hdgzView(),
            SizedBox(
              height: 8,
            ),
          ],
        );
      },
    );
  }

  Widget _groupfzView() {
    return Column(
      children: <Widget>[
        wrapListView(_listEntity),
        SizedBox(
          height: 8,
        ),
        WidgetUtils.showWidthBoxBotton(
            '今日已参与${_groupDetailEntity.todayJoinSeq}次',
            borderColor: Colours.title_white,
            boxColor: Colours.title_white,
            textColor: Colours.text_2222),
        SizedBox(
          height: 16,
        ),
        WidgetUtils.showWidthBoxBotton(
            '当前专区待返代理券${_groupDetailEntity.myNoWatchGuanGaoCt}张',
            borderColor: Colours.title_white,
            boxColor: Colours.title_white,
            textColor: Colours.text_2222),
      ],
    );
  }

  Widget _hdgzView() {
    return Container(
      alignment: Alignment.center,
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
      decoration: new BoxDecoration(
        color: Colours.title_white,
      ),
      margin: const EdgeInsets.symmetric(horizontal: 4, vertical: 0),
      child: Column(
        children: <Widget>[
          WidgetUtils.getTextColorView(
              '活动规则', Colours.text_2222, Dimens.FONT_SIZE_16),
          SizedBox(
            height: 16,
          ),
          ObjectUtil.isEmptyString(_groupDetailEntity.remark)
              ? Container()
              : FadeInImage.assetNetwork(
                  image: _groupDetailEntity.remark,
                  placeholder: 'images/picture_loading.png',
                  fit: BoxFit.cover,
                ),
        ],
      ),
    );
  }

  Widget wrapListView(List<SelectiontEntity> list, {Function checkBoxCall}) {
    return Container(
      alignment: Alignment.centerLeft,
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
      decoration: new BoxDecoration(
        color: Colours.pt_red,
      ),
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.symmetric(
              horizontal: 8,
            ),
            child: WidgetUtils.getTextColorView('当前有${list.length}人正在推广',
                Colours.text_2222, Dimens.FONT_SIZE_16),
          ),
          SizedBox(
            height: 16,
          ),
          Wrap(
            direction: Axis.horizontal,
            alignment: WrapAlignment.start,
            spacing: 8,
            runSpacing: 16,
            crossAxisAlignment: WrapCrossAlignment.start,
            children: list.map((SelectiontEntity entity) {
              return _departmentName(list, entity);
            }).toList(),
          ),
          SizedBox(
            height: 16,
          ),
          Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.symmetric(
              horizontal: 8,
            ),
            child: WidgetUtils.getRichTextView(_richList),
          ),
          SizedBox(
            height: 16,
          ),
        ],
      ),
    );
  }

  Widget _departmentName(List<SelectiontEntity> list, SelectiontEntity entity) {
    return GestureDetector(
      onTap: (() {
        setState(() {
          if (entity.isEnd) {
            _listEntity
              ..add(SelectiontEntity()..title = (list.length + 1).toString());
          }
        });
      }),
      child: Container(
          width: 32,
          color: Colours.transparent,
          child:
              //  entity.isEnd
              //     ? Column(
              //         mainAxisAlignment: MainAxisAlignment.center,
              //         crossAxisAlignment: CrossAxisAlignment.center,
              //         children: <Widget>[
              //           Icon(
              //             Icons.add,
              //             color: Colours.themeColor,
              //             size: 48,
              //           ),
              //         ],
              //       )
              //     :
              Column(
            children: <Widget>[
              Icon(
                Icons.person,
                color: Colours.themeColor,
                size: 32,
              ),
              SizedBox(
                height: 4,
              ),
              WidgetUtils.getTextColorView(
                  '${entity.title}', Colours.text_2222, Dimens.FONT_SIZE_16),
            ],
          )),
    );
  }

  @override
  void dispose() {
    _initViewSubscription?.cancel();
    _refeshSubscription?.cancel();
    _videoCompletetSubscription?.cancel();
    super.dispose();
  }
}
